import { get } from './redis';

const WebSocket = require('ws');
/**
 * wss
 */
export default class JngSocket{
  constructor({ port, heart }){
    this._ws = null
    this._port = port
    this._heart = heart || false
  }

  create(){
    const WebSocketServer = WebSocket.Server;
    // 实例化:
    this._ws = new WebSocketServer({
      port: this._port
    },() => {
      console.log(`websocket ready at ws://localhost:${this._port}`)
    });
  }

  // connection
  onConnection(callback){
    this._ws.on("connection", (ws) => {
      callback(ws)
    })
  }

  // 广播消息
  broadcast(data){
    if(this._ws.clients.size > 0){
      this._ws.clients.forEach(function (client) {
        client.send(data);
      });
    }
  }

  // 创建消息格式
  createMessage(type, data) {
    // messageIndex ++;
    return JSON.stringify({
        // id: messageIndex,
        type: type,
        data: data
    });
  }

  // 监听消息
  onMessage(ws, callback){
    ws.on('message', function incoming(message) {
      callback(message)
    });
  }
}

/**
 * create webSocket
 */

var wss = new JngSocket({port: 'PORT'})
wss.create()

wss.onConnection((ws) => {
  wss.onMessage(ws, (msg) => {
    if(msg == 'live'){
      setTimeout(() => {
        ws.send('LIVE TRUE')
      }, 3000);
    }
  })
})

export { wss }

